var isTrue=false;     //定义是否显示增长率的变量
/**
 * Created by Administrator on 2016-08-21.
 */
var host_path_action_report_analysis_indicator = "/report/analysis/indicator.do";
var host_path_action_report_analysis_indicatorType= "/report/analysis/indicatorType.do";
var allYear="/resources/js/views/allYear.do";
function loadYear(){
	$.get(allYear, function (json) {
		$("#comboboxYear").combobox({
			textField:"text",
			valueField:"id",
			width:'100px',
			height:'28px',
			data:json,
			multiple:true,
			editable:false,
			formatter:function(row){
				var opts;
				if(row.select=="true"){
					row.selected=true;
					opts = "<input type='checkbox' name='year' checked='checked' id='"+row.id+"' value='"+row.id+"'>"+row.text+"</input>";
				}else{
					opts = "<input type='checkbox' name='year' id='"+row.id+"' value='"+row.id+"'>"+row.text+"</input>";
				}
				return opts;
			},
			panelHeight:"auto",
			panelWidth:'100px',
			panelAlign:'left',
			onSelect:function(rec) {
				oCheckbox = document.getElementById(rec.id);
				oCheckbox.checked=true;
				query(page,pageSize);
			},
			onUnselect:function(rec){
				oCheckbox = document.getElementById(rec.id);
				oCheckbox.checked=false;
				query(page,pageSize);
			}
			// ,
			// onLoadSuccess:function(){
			// 	queryList();
			// }
		});
	},'json');
}
function funcSort (a,b) {
	return a-b;
}

var host_path_action_report_query_depart_indicator="/report/query/depart/indicator.do";
//同类型指标的checkbox改可选或不可选
function modifyCheckBox(row, data){
	//页面已经有数据
	if(data!=null && data!="" && data!=''){
		for(var i=0;i<data.rows.length;i++){
			//选中了其中一行
			if(row!="" && row !='' && row.length==1){
				//如果有选中的数据,和选中数据单位不一样的,其他数据都置为不可选择的状态
				if(data.rows[i].unit != row[0].unit){
					$("input[type='checkbox'][name='ck']")[i].disabled = true;
				}else{
					$("input[type='checkbox'][name='ck']")[i].disabled = false;
					//取消选中状态
//					$(this).datagrid('unselectRow', index);
				}
				//一行也未选中,所有的元素都是未选中(可选状态)
			}else{
				$("input[type='checkbox'][name='ck']")[i].disabled = false;
			}
		}
	}
}

function replaceStr(value){
	return value.toString().replace(/&nbsp;/g, "");
}
//根据指标的领域进行展示
function showFieldAnalysis(){
	var row=$('#annualAnalysis_tt').datagrid('getSelections');
	var data=$('#annualAnalysis_tt').datagrid('getData');
//	modifyCheckBox(row, data);
	if(row!="" && row !='' && row.length>0){
		getDate(row, true);
	}
}
//根据指标的部门进行展示
function showAnnualAnalysis(){
	var data=$('#annualAnalysis_tt').datagrid('getData');
	var row=$('#annualAnalysis_tt').datagrid('getSelections');
//	modifyCheckBox(row, data);
	if(row!="" && row !='' && row.length>0){
		getDate(row, false);
	}
}

var isShow=false;
var zbname = [];
var series = [];
var jsonXData = [];
var conceal={};
//从服务器获取数据

function getDate(row){
	var indicator = 0;
	var departIds = 0;
	var departIdsArray = [];
	for (var i = 0; i < row.length; i ++){
		indicator+=row[i]['indicator']+",";
		if(departIdsArray.indexOf(row[i]['departid'])!=0){
			departIdsArray.push(row[i]['departid']);
			departIds+=row[i]['departid']+",";
		}
	}
	indicator=indicator.substring(0,indicator.length-1);
	departIds=departIds.substring(0,departIds.length-1);

	var yeares =$('#comboboxYear').combobox('getText');
	var years = [];
	if(yeares!=null ||yeares!='' || yeares!=undefined){
		years=yeares.split(',');
	}
	if(years.length>1){
		years.sort(funcSort);
	}

    var formsid=$('#formid').combobox('getValue');
	$.get(host_path_action_report_query_depart_indicator+'?years='+yeares+'&departids='+departIds+'&indicatorids='+indicator+'&formsid='+formsid, function (result) {
		var datas = result.data.results;
		var yearCount = 0;
		if(years!=null && years!=undefined){
			yearCount = years.length;
		}
		var size = 0;
		if(datas!=null){
			size = datas.length;
		}
		zbname = [];
		series = [];
		jsonXData = [];
		conceal={};
//-------------------------------------------加绝对值指标---------------------------------------
		for (var i = 0; i < size; i ++){
			var aav = new Object();
			var aav2 = new Object();  //加绝对值指标
			datas[i].iname = replaceStr(datas[i].iname);
			zbname.push(datas[i].iname);
			if(isTrue){ //点击增长率出现
			zbname.push(datas[i].iname+'增长速度%');//加绝对值指标
			}
			conceal[datas[i].iname+'增长速度%']=false;
			aav.name = datas[i].iname;
			aav.type = 'bar';
			aav.barMaxWidth=80;
			aav.label={normal: {show: true,position: 'top'}};
			var arr=[];
			aav2.name = datas[i].iname+'增长速度%';//加绝对值指标
			aav2.type = 'line';//加绝对值指标
			aav2.label={normal: {show: true,position: 'top'}};
			aav2.yAxisIndex = '1' ;
			var arr2=[];//加绝对值指标
//加绝对值指标---------------------------------------
			for(var j = 0; j < yearCount; j++){
				if(datas[i][years[j]]!=undefined){
					if(j==0){
						arr2.push(0);
					}else if(((datas[i][years[j]].split("_")[2]-datas[i][years[j-1]].split("_")[2])/datas[i][years[j-1]].split("_")[2])*100==Infinity){
						var avg=0;
						arr2.push(changeNum(avg));
					}else{
						var avg=((datas[i][years[j]].split("_")[2]-datas[i][years[j-1]].split("_")[2])/datas[i][years[j-1]].split("_")[2])*100;
						arr2.push(changeNum(avg));
					}
					arr.push(changeNum(datas[i][years[j]].split("_")[2]));
					jsonXData.push(years[j]);
				}
			}
			aav.data = arr;
			aav2.data=arr2;//加绝对值指标
			series.push(aav);
			if(isTrue) {
				series.push(aav2); //加绝对值指标
			}
		}
		if(row){
			isShow=false;
			if(isTrue){
				isShow=true;
			}
			showData(zbname, series, jsonXData,conceal,isShow);
		}
	}, 'json');
}

function changeNum(a) {
	return Number(a).toFixed(2);
}

//显示效果
function showData(zbname, series, jsonXData ,conceal,isShow){
	$("#tabDiv").height("370px");
	$("#annualAnalysis_containerzhuzi").height("360px");
	$("#annualAnalysis_containerzhuzi").width($("#tabDiv").width()-40);
	var myChart = echarts.init(document.getElementById('annualAnalysis_containerzhuzi'),'macarons');
	$('#annualAnalysis_change').show();
	$('#annualAnalysis_colorSelect').empty();
// 指定图表的配置项和数据
	option = {
		legend: {
			data: zbname     //柱状图最上端所显示的所有数据名字
		},
		tooltip: {
			trigger: 'axis'
		},
		toolbox: {
			show: true,
			orient:'vertical',
			y:'center',
			itemGap:12,
			itemSize:17,
			padding: 5,
				feature: {
				mark: {show: true},
				myTool4 : {
				show : true,
				title : '折线图',
				icon : "M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4",
				onclick : function (){
					for(var a=0; a<option.series.length; a++){
						option.series[a].type = "line"
						// option.series[a].itemStyle = {normal: {areaStyle: {type: 'default'}}};
					}
					for(var i=0,len=option.series.length;i<len;i++){
						if(typeof option.series[i].label != "undefined"){
							option.series[i].label.normal.position="top"
						}
					}
					myChart.setOption(option);

					for(var d=0; d<option.series.length; d++){
						delete option.series[d].itemStyle

					}
				}
			},
				magicType: {show: true, type: ['bar','stack','tiled','pie','funnel']},
				restore: {show: false},
				myTool : {
					show : true,
					title : '横向',
					icon : 'image:///resources/images/1.png',  //注意一下图片的路径
					onclick : function (){
						for(var i=0,len=option.series.length;i<len;i++){
							if(typeof option.series[i].label != "undefined"){
								option.series[i].label.normal.position="right"
							}
						}
						var seriesV=option.series;
						myChart.setOption({
							xAxis: [
								{
									type: 'value'
								}
							],
							yAxis: [
								{
									type: 'category',
									data: jsonXData
								}
							],
							series:seriesV
						});
					}
				},myTool1 : {
					show : true,
					title : '竖向',
					icon : 'image:///resources/images/3.png',
					onclick : function (){
						for(var i=0,len=option.series.length;i<len;i++){
							if(typeof option.series[i].label != "undefined"){
								option.series[i].label.normal.position="top"
							}
						}
						var seriesV=option.series;
						myChart.setOption({
							xAxis: [
								{
									type: 'category',
									data: jsonXData

								}
							],
							yAxis: [
								{
									type: 'value'
								}
							],
							series:seriesV
						});
					}
				},myTool2 : {
					show : true,
					title : '增长率',
					icon : 'image:///resources/images/2.png',
					onclick : function (){
						isTrue=true;
						showAnnualAnalysis();
					}
				},myTool3 : {
					show : true,
					title : '还原',
					icon:"M3.8,33.4 M47,18.9h9.8V8.7 M56.3,20.1 C52.1,9,40.5,0.6,26.8,2.1C12.6,3.7,1.6,16.2,2.1,30.6 M13,41.1H3.1v10.2 M3.7,39.9c4.2,11.1,15.8,19.5,29.5,18 c14.2-1.6,25.2-14.1,24.7-28.5",
					onclick : function (){
						isTrue=false;
						showAnnualAnalysis();
					}
				},saveAsImage : {
					show : true,
					title : '保存为图片',
					type : 'png',
					lang : ['点击保存']
				}
			}
		},
		calculable: true,
			xAxis: [
			{
				type: 'category',
				boundaryGap : true,
				data: jsonXData
			}
		],
			yAxis : [
			{
				type : 'value',
				axisLabel : {
					formatter: '{value}'
				}
			},
			{
				type : 'value',
				axisLabel : {
					formatter: '{value}'
				},
				show: isShow,
			}
		],
			series: series,
		// label: {
		// 	normal: {
		// 		show: true,
		// 		textStyle: {color: '#000'}
		// 	}
		// },
			color:['#63cee0','#63e0a7','#d2e063','#cc99cc','#ffcccc','#1962ad','#b47e8e']
	};
// 使用刚指定的配置项和数据显示图表。
	myChart.setOption(option);
	$('#annualAnalysis_dark').click(function () {
		myChart = echarts.init(document.getElementById('annualAnalysis_containerzhuzi'),'dark');
		myChart.setOption(option);
	});
	$('#annualAnalysis_infographic').click(function () {
		myChart = echarts.init(document.getElementById('annualAnalysis_containerzhuzi'),'infographic');
		myChart.setOption(option);
	});
	$('#annualAnalysis_macarons').click(function () {
		myChart = echarts.init(document.getElementById('annualAnalysis_containerzhuzi'));
		myChart.setOption(option);
	});
	$('#annualAnalysis_vintage').click(function () {
		myChart = echarts.init(document.getElementById('annualAnalysis_containerzhuzi'),'vintage');
		myChart.setOption(option);
	});
	$('#annualAnalysis_default').click(function () {
		myChart = echarts.init(document.getElementById('annualAnalysis_containerzhuzi'),'macarons');
		myChart.setOption(option);
	});
	myChart.setOption(option);
	$('#annualAnalysis_landscape').click(function () {
		myChart.setOption({
			xAxis: [{type: 'value'}],
			yAxis: [{type: 'category', data: jsonXData}]
		})
	});
	myChart.setOption(option);
	$('#annualAnalysis_reset').click(function () {
		myChart.setOption({
			xAxis: [{type: 'category',data: jsonXData}],
			yAxis: [{type: 'value'}]
		})
	});
	myChart.setOption(option);
	var color = ['#63cee0','#63e0a7','#cc99cc','#ffcccc','#ffffcc','#1962ad','#b47e8e']; 
	var node=[];
	var para=[];
	var colorId=[];
	for (var m=0;m<2*zbname.length;m++){
		var element=document.getElementById('annualAnalysis_colorSelect');
		if(m%2==0){
			var paraSon = document.createElement('div');
			paraSon.className = 'paraSon';
			element.appendChild(paraSon);
		}
		para[m]=document.createElement('div');
		paraSon.appendChild(para[m]);
		// para[m].style.cssFloat='left';
		para[m].style.height='30px';
		para[m].style.color='#1196db';

		if(m%2==0){
			para[m].className = 'colorText';
		} else {
			para[m].className = 'colorShow';
		}

		colorId.push('annualAnalysis_colorNumber'+m);
		$(para[m]).attr('id',colorId[m]);
		if(m%2==0) {
			node[m] = document.createTextNode(zbname[m/2]);
			para[m].appendChild(node[m]);
			para[m].style.marginLeft="15px";
		}else{
			$('#annualAnalysis_colorNumber' + m).html('').append('<input type="text"  style="display: none" name="color'+m+'" data-palette='+
				'["#FF0000","#FFB90F","#FFFF00","#73bf44","#00FFFF","#EE00EE","#C1C1C1","#CAE1FF","#0000ff","#836FFF"]'+
				' id="color'+m+'"value="#00B8D4"/>');
			var iannualAnalysis_colorNumber = document.getElementById('annualAnalysis_colorNumber'+m);
			iannualAnalysis_colorNumber.style.marginTop = "7px";
			iannualAnalysis_colorNumber.style.marginLeft = "10px";
			var iColor  = document.getElementById('color'+m);
			$('#color'+m).paletteColorPicker();
			var iDiv = document.getElementsByTagName("div");
			var index = 0;
			for(var i=0;i<iDiv.length;i++){
				if(iDiv[i].className == "palette-color-picker-button"){
					iDiv[i].number = index++;
					iDiv[i].first=0
					iDiv[i].onclick = function () {
						if(this.first==0){
							this.first++;
						}else{
							var rgbColor=$('#color'+(2*this.number+1)).val();
							color[this.number]=rgbColor;
							myChart.setOption({
								color: color
							})
						}
					}
				}
			}
		}
	}
}

var cityAccount="/indicator/count/type.do";   
var dataLength=0;
//指标占比分析出图
function showImage(index,type){
	var yeares=document.getElementsByName("year");
	var yearList= [];
	for (var i=0;i<yeares.length;i++){
			yearList.push(yeares[i].value);
	}
	dataLength=yearList.length;
	
	var year=yearList[index];
	var formsid=$('#formid').combobox('getValue');

	$.get(cityAccount, {"years":year,"formsid":formsid}, function (json) {
		if(json.code != 200){
			return;
		}
		var data=json.data;
		var total=data.size;
		data=data["results"];
		var yAxisDatas=[];
		var seriesDatas=[];
		for (var i = 0; i < data.length; i++) {
			yAxisDatas.push(data[i].name);
			seriesDatas.push(parseFloat(((data[i].count/total)*100).toFixed(2)));
		}

		$("#annualAnalysis_containerzhuzi2").width($("#tabDiv").width()-40);
		$("#annualAnalysis_containerzhuzi2").height("380px");
	var myChart = echarts.init(document.getElementById('annualAnalysis_containerzhuzi2'),'macarons');
	var optionText;
	if(type){
		var citySelect= $('#fieldAnalysis_citySelect').combobox("getText");
		optionText=	year+'年'+citySelect+'各领域指标占比分析（%）';
	}else{
		optionText=	year+'年省级各领域指标占比分析（%）';
	}
//指定图表的配置项和数据
		var	option2  = {
				color:['#71e9f4'],
			    // title : {
			    // 	text: optionText,
			    // },
			    tooltip : {
			        trigger: 'axis'
			    },
			    toolbox: {
			        show : true,
			        feature : {
			            mark : {show: true},
			            saveAsImage : {show: true}
			        }
			    },
			    grid:{
			    	y2: 140
			    },
			    calculable : true,
			    xAxis : [
		             {
			            type : 'category',
			            data : yAxisDatas,
					    axisLabel: {
							interval: 0, //横轴信息全部显示  
							rotate: -30, //-30度角倾斜显示  
						}        
				     }
			    ],
			    yAxis : [
		             {
			            type : 'value',
			            boundaryGap : [0, 0.01]
				     }     
			    ],
			    series : [
			        {
			            name:'比例',
			            type:'bar',
			            itemStyle : { normal: {label : {show: true, position: 'top',  formatter: '{c}%'}}},
			            data:seriesDatas
			        }			        
			    ],
			    color:['#63cee0','#63e0a7','#d2e063','#e09e63','#e063d5','#6663e0','#e06390']
			};
			                    
		myChart.setOption(option2,true);
		var zr = myChart.getZr();
		
		var icon0 = new echarts.graphic.Circle({
		    shape: { r: 20 },
		    style: {
		        text: '<',
		        fill: '#eee'
		    },
		    position: [20, zr.getHeight() / 2]
		});
		
		var icon1 = new echarts.graphic.Circle({
		    shape: { r: 20 },
		    style: {
		        text: '>',
		        fill: '#eee'
		    },
		    position: [zr.getWidth() - 20, zr.getHeight() / 2]
		});
		
		var group = new echarts.graphic.Group();
		group.add(icon0);
		group.add(icon1);
		zr.add(group);
		icon0.on('click', function () {
			index -= 1;
			if (index < 0) {
				index += dataLength;
			}
			showImage(index)
		});
		icon1.on('click', function () {
			index = (index + 1) % dataLength;
			showImage(index);
		});
	},"JSON");
}


//增长率点击事件
$('#annualAnalysis_growth').click(function () {
	isTrue=true;
	showAnnualAnalysis();
});
//还原增长率折线图为单柱状图
$('#annualAnalysis_restore').click(function () {
	isTrue=false;
	showAnnualAnalysis();
});

function queryByAreaAndIndicators(curPage, pageSize, fromPage) {

	curPage = parseInt(curPage);
	pageSize = parseInt(pageSize);

	var yeares = $('#comboboxYear').combobox('getText');
	var yearList = [];
	if(yeares!=null ||yeares!='' || yeares!=undefined){
		yearList=yeares.split(',');
	}
	if(yearList.length>1){
		yearList.sort(funcSort);
	}
	var formsid=$('#formid').combobox('getValue');

	var reportShowColumns = [];
	var ck = {
		title : '',
		field : 'ck',
		checkbox : true,
		width : 90
	};
	reportShowColumns.push(ck);
	reportShowColumns.push(defineTableReportAllColumns["iname"]);//指标名称
	reportShowColumns.push(defineTableReportAllColumns["code"]);//指标名称
	reportShowColumns.push(defineTableReportAllColumns["unit"]);//计量单位
	reportShowColumns.push(defineTableReportAllColumns["places"]);//小数位数

	for (var i = 0; i < yearList.length; i++) {
		var c = {title : yearList[i], field : yearList[i], width : 90,align:"center",
			formatter : function(value, row, index) {
				// 数据上报的类型_每年的目标值_数值_显示数据展示时效果的规则_每年的备注
				var tempValue;
				if(value!=null && value.indexOf('_')!=-1){
					tempValue = value.split('_')[2];
				}
				if(tempValue===null||tempValue==""||tempValue=="null"||tempValue=="NULL"){
					return "";
				}else{
					return tempValue;
				}
			}
		};
		reportShowColumns.push(c);
	}
	reportShowColumns.push(defineTableReportAllColumns["sname"]);//资料来源

	var indicators=0;
	var row=$('#ttIndicator').datagrid('getSelections');
	if(row!="" && row !='' && row.length>0){
		for (var i = 0; i < row.length; i ++){
			indicators+=row[i]['id']+",";
		}
		indicators=indicators.substring(0, indicators.length-1);
	}
	var level;
	var areaid;

    // alert(fromPage);

	if(fromPage=='PROVINCE'){
		level=2;
	}else if(fromPage=='CITY'){
		areaid= $('#fieldAnalysis_citySelect').combobox('getValue');
		level=3;
	}else if(fromPage=='COUNTY'){
		areaid= $('#fieldAnalysis_citySelect').combobox('getValue');
		level=4;
	}

	$.get(host_path_action_report_analysis_indicator, {"years": yeares,"indicators":indicators, "areaid":areaid,"level":level,"page": curPage, "pageSize": pageSize,"formsid":formsid}, function (json) {
		if(json.code!=200) {
			clearData();
			return;
		}
		var data = json.data;
		var total= 0;
		if(data!=null){
			total = data.size;
		}
		var totalPage = Math.ceil(total / pageSize);
		var start = (curPage - 1) * pageSize;
		var dataLength = 0;
		data = data["results"];
		if (data != null) {
			dataLength = data.length;
		}
		$('#annualAnalysis_tt').datagrid( {
			fitColumns: true,
			frozen:true,
			columns:[
				reportShowColumns
			],
			collapsible: true,
			singleSelect : false,// 是否单选
			checkOnSelect: true,//选中行后,checkbox选中
			selectOnCheck: true,//选中行后,checkbox选中
			loadMsg: '数据加载中,请稍后......',
//              删除之后，不显示总数据数的排序号，只显示本页数的排序号
			pageNumber: curPage,//显示数据列用
			pageSize: pageSize,
			pageList: [30, 500, 1000, 1500],
			// rownumbers: isShow,
//              删除之后，不显示总数据数的排序号，只显示本页数的排序号
			pagination: true,//打开翻页功能
			striped:true,//表格奇偶渐变色
			data: data,
			onClickRow:function(index, data) {
				//显示页面效果
				$("#annualAnalysis_containerzhuzi").height("360px");
				$("#annualAnalysis_containerzhuzi").width("98%");
				// show.tableshow();
				$("#annualAnalysis_chart").panel("expand",true);
				$("#annualAnalysis_colorSelect").css({display:"block"});
				$("#none").css({display:"block"});
				$("#tabb").css({marginTop:"0px"});

				showFieldAnalysis();
			}
		});

		var p = $('#annualAnalysis_tt').datagrid('getPager');
		$(p).pagination({
			total: total,
			pageList: [30, 500, 1000, 1500],
			pageSize: pageSize,
			pageNumber: curPage,
			beforePageText: '第',
			afterPageText: '页    共 ' + totalPage + ' 页',
			displayMsg: '当前显示 ' + (start + 1) + '-' + (start + dataLength) + ' 条记录 共 ' + total + ' 条记录',
			onSelectPage: function (curPage, pageSize) {
				queryByAreaAndIndicators(curPage, pageSize, fromPage);
			},
			onChangePageSize: function (ps) {
				pageSize = ps;
			}
		});
	}, 'json');
}